/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 * limitations under the License.
 */

package hadss.avoid_area

import androidx.core.util.Consumer
import androidx.window.java.layout.WindowInfoTrackerCallbackAdapter
import androidx.window.layout.FoldingFeature
import androidx.window.layout.WindowLayoutInfo
import io.flutter.plugin.common.EventChannel
import org.json.JSONObject


/**
 * 获取折叠屏状态
 */
class FolderStateStreamHandler(private val windowInfoTracker: WindowInfoTrackerCallbackAdapter) :
    EventChannel.StreamHandler,
    Consumer<WindowLayoutInfo> {
    private var windowEventSink: EventChannel.EventSink? = null
    private var featureJson: JSONObject =
        JSONObject("{\"state\":0,\"orientation\":0,\"bounds\":{\"left\":0,\"right\":0,\"top\":0,\"bottom\":0}}")

    override fun accept(value: WindowLayoutInfo) {
        val feature = value.displayFeatures.filterIsInstance<FoldingFeature>().firstOrNull()
        featureJson = JSONObject("{\"state\":0,\"orientation\":0,\"bounds\":{\"left\":0,\"right\":0,\"top\":0,\"bottom\":0}}")
        feature?.let {
            featureJson = JSONObject()
            featureJson.put(
                "state", when (feature.state) {
                    FoldingFeature.State.FLAT -> 1
                    FoldingFeature.State.HALF_OPENED -> 3
                    else -> 2
                }
            )
            featureJson.put(
                "orientation", when (feature.orientation) {
                    FoldingFeature.Orientation.VERTICAL -> 1
                    else -> 0
                }
            )
            featureJson.put("bounds", JSONObject().apply {
                put("left", feature.bounds.left)
                put("right", feature.bounds.right)
                put("top", feature.bounds.top)
                put("bottom", feature.bounds.bottom)
            })
        }
        windowEventSink?.success(featureJson.toString())
    }

    override fun onListen(arguments: Any?, eventSink: EventChannel.EventSink?) {
        windowEventSink = eventSink
        featureJson.let {
            windowEventSink?.success(featureJson.toString())
        }
    }

    override fun onCancel(arguments: Any?) {
        windowInfoTracker.removeWindowLayoutInfoListener(this)
    }
}